﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using RApplication = Autodesk.Revit.ApplicationServices.Application;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.DB.Structure;
using Autodesk.Revit.UI.Selection;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB.ExtensibleStorage;

using Autodesk.Revit.DB.Architecture;

using Autodesk.Revit.DB.Mechanical;

using Autodesk.Revit.DB.Electrical;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Reflection;
using Autodesk.Revit.UI.Events;
using System.Windows;

using System.IO;
using System.Collections;
using System.Data;
using System.IO.Ports;
using System.Threading;
using System.Diagnostics;


using System.Diagnostics;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;



namespace YJKPostCommandElec
{
    [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
    [Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)]
    public class PostCommandArcWire : IExternalCommand
    {
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {


            Document doc = commandData.Application.ActiveUIDocument.Document;
            UIDocument uiDoc = commandData.Application.ActiveUIDocument;
            Transaction ts = new Transaction(doc);
            int iokf = 0;
            MepGeoFunctions.YJKMEPMath.GetViewifOk(doc, uiDoc, out iokf);
            if (iokf == 0)
            {
                string messagez = "平面图";
                TaskDialog.Show("请选择", messagez);
                goto label2;
            }
            ts.Start("transtion");

            RevitCommandId cid = RevitCommandId.LookupPostableCommandId(PostableCommand.ArcWire);
            commandData.Application.PostCommand(cid);
            ts.Commit();
        label2:
            return Result.Succeeded;
        }

    }
        [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
        [Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)]
        public class PostCommandChamferedWire : IExternalCommand
        {
            public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
            {



                Document doc = commandData.Application.ActiveUIDocument.Document;
                UIDocument uiDoc = commandData.Application.ActiveUIDocument;
                Transaction ts = new Transaction(doc);
                int iokf = 0;
                MepGeoFunctions.YJKMEPMath.GetViewifOk(doc, uiDoc, out iokf);
                if (iokf == 0)
                {
                    string messagez = "平面图";
                    TaskDialog.Show("请选择", messagez);
                    goto label2;
                }
                //       FilteredElementCollector wireCollector = new FilteredElementCollector(doc);
                //       wireCollector.OfClass(typeof(Wire)).OfCategory(BuiltInCategory.OST_Wire);

                /*    var exitLamp = from element in wireCollector
                                   where element.LevelId==uiDoc.ActiveView.GenLevel.Id
                                   select element; */

                ts.Start("transtion");
                RevitCommandId cid = RevitCommandId.LookupPostableCommandId(PostableCommand.ChamferedWire);
                commandData.Application.PostCommand(cid);
                ts.Commit();
            /*         FilteredElementCollector wireCollectorafter = new FilteredElementCollector(doc);
                     wireCollectorafter.OfClass(typeof(Wire)).OfCategory(BuiltInCategory.OST_Wire);
               /*      var exitLampafter = from element in wireCollectorafter
                                    where element.LevelId == uiDoc.ActiveView.GenLevel.Id
                                    select element; */
            /*     string name1 = "照明";
                 foreach (Element e in wireCollectorafter)
                 {
                     ElementId ida = e.Id;
                     foreach (Element eb in wireCollector)
                    {
                        if (eb.Id==ida)
                        {
                            goto label0;
                        }
                    }

                    Wire wire1 = e as Wire;
                    ts.Start("transtion");
                    Parameter parameter1 = wire1.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS);
                    parameter1.Set(name1);
                    ts.Commit();
                label0:
                    int ij = 0;
              
                 } */

            label2:
                return Result.Succeeded;
            }
        }
    }
    namespace YJKCommandElec
    {
        [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
        [Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)]
        public class AssignWireAttribution1 : IExternalCommand
        {
            public static string filespathE = "";
            public static string conduitXmlfileName = "YJKElectricConduitSizes.xml";
            public static string wireXmlfileName = "YJKElectricWireSizes.xml";
            public static  UIApplication  uiapp = null;
            public static string  sharename = "YJK_Electric_Shared_Parameters.txt";
            public static Document doc;
            public string defaultfileName = "YJKRevitWireAssign.txt";
            public static List<YJKMepElecWeak.WireTypeSelfDataDef> listWire=new List<YJKMepElecWeak.WireTypeSelfDataDef>();
            public static List<YJKMepElecWeak.ConduitTypeSelfDataDef> listConduit=new List<YJKMepElecWeak.ConduitTypeSelfDataDef>() ;
            public static  Autodesk.Revit.ApplicationServices.Application application = null;
            public static int mark = 1;
            public  YJKMepElecWeak.WireAssignParameters avariable = new YJKMepElecWeak.WireAssignParameters();
           protected UIApplication m_uiApp;

		    protected UIDocument m_uiDoc;
      
	     	protected Autodesk.Revit.ApplicationServices.Application m_app;

	     	protected Document m_doc;

		    protected static double precision = 1E-06;
            protected virtual Result YJKExcute(ExternalCommandData cmdData, ref string message, ElementSet elements)
            {
                return Autodesk.Revit.UI.Result.Succeeded;
            }


          
            public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
            {
                doc = commandData.Application.ActiveUIDocument.Document;
                UIDocument uiDoc = commandData.Application.ActiveUIDocument;
                UIApplication app1 = uiDoc.Application;
                application = commandData.Application.Application;
                uiapp = app1;
                int iokf = 0;
                MepGeoFunctions.YJKMEPMath.GetViewifOk(doc, uiDoc, out iokf);
                if (iokf == 0)
                {
                    string messagez = "平面图";
                    TaskDialog.Show("请选择", messagez);
                    goto label2;
                }

        	this.m_uiApp = commandData.Application;
			this.m_uiDoc = this.m_uiApp.ActiveUIDocument;
			this.m_app = this.m_uiApp.Application;
			this.m_doc = this.m_uiDoc.Document;
		//	return this.YJKExcute(commandData, ref message, elements);
            return AssignWireAttribution.YJKExcute(commandData, ref message, elements);
             
       /*         int iok=0;
                Wire wire=null;
                wire = GetWireObj(doc, uiDoc, ref iok);
                if (iok==1)
                {
                   
                }
                else
                    goto label2;

                YJKMepElecWeak.WireAssignParameters a=new YJKMepElecWeak.WireAssignParameters ();
                YJKMepElecWeak.WireAttrbutionDlg dlg = new YJKMepElecWeak.WireAttrbutionDlg ();
                listWire = GetWireType(doc);
                listConduit = GetConduitType(doc);
                dlg.bWire = wire;
                dlg.initDefault();
             
                GetWireAttibute(ref a, wire,dlg);
         //       return Result.Succeeded;
                dlg.aapara = a;
                dlg.listWire =listWire ;

                dlg.listConduit = listConduit;
               
                dlg.initDefaultValue(a);
                dlg.TopMost = true;
                dlg.Show();
                AssignWiretAction(doc, uiDoc, dlg,ref a);
              
                WriteVariable(defaultfileName, a);
                dlg.Dispose(); */
            label2:
                return Result.Succeeded;
            }
        }
            public class AssignWireAttribution : AssignWireAttribution1
            {
                [DllImport("user32.dll", EntryPoint = "SendMessageA")]
                public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

              protected override Result YJKExcute(ExternalCommandData cmdData, ref string message, ElementSet elements)
	    	 {
                if (AssignWireAttribution._hWndRevit == null)
			   {
                   AssignWireAttribution._hWndRevit = new WindowHandle(Process.GetCurrentProcess().MainWindowHandle);
		     	}
			   Document document = cmdData.Application.ActiveUIDocument.Document;
			   YJKMepElecWeak.WireAttrbutionDlg dlg = null;
		    	try
			   {
				   dlg = new YJKMepElecWeak.WireAttrbutionDlg (cmdData);

                   Wire wire = null;
                   YJKMepElecWeak.WireAssignParameters a = new YJKMepElecWeak.WireAssignParameters();
                   listWire = GetWireType(doc);
                   listConduit = GetConduitType(doc);
                   dlg.bWire = wire;
                   dlg.initDefault();

                   GetWireAttibute(ref a, wire, dlg);
                   //       return Result.Succeeded;
                   dlg.aapara = a;
                   dlg.listWire = listWire;

                   dlg.listConduit = listConduit;

                   dlg.initDefaultValue(a);
                   dlg.TopMost = true;
                   avariable = a;
                   dlg.Show(AssignWireAttribution._hWndRevit);
			   }
			   catch (Exception ex)
			  {
				MessageBox.Show(ex.Message);
				if (dlg != null)
				{ 
					dlg.Close();
				}
				return Autodesk.Revit.UI.Result.Failed;
			  }
			  int wMsg = 7;
              AssignWireAttribution.SendMessage(AssignWireAttribution._hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
              Result result = Result.Succeeded;
			//  for (;;)
			  {
				Transaction transaction = new Transaction(this.m_doc, "ddd");
             //   AssignWiretAction1(doc, m_uiDoc, dlg, ref avariable);
                string statusPrompt = "请选择导线";
                WiresCorrection.WiresCorrectionAct.SelectionWireFilter selectionWireFilter = new WiresCorrection.WiresCorrectionAct.SelectionWireFilter();
                List<Reference> r2 = new List<Reference>();
                Selection s1 = m_uiDoc.Selection;
                r2 = (List<Reference>)s1.PickObjects(ObjectType.Element, selectionWireFilter, statusPrompt);
                Element e = null;
                Wire wiret = null;
                Reference r1 = null;
                List<Wire> listwiret = new List<Wire>();
                for (int ki = 0; ki < r2.Count; ki++)
                {
                    r1 = r2[ki];
                    doc.GetElement(r1);
                    wiret = e as Wire;
                    listwiret.Add(wiret);
                }
                YJKMepElecWeak.WireAssignParameters Dia = new YJKMepElecWeak.WireAssignParameters();
      //          YJKMepElecWeak.WireAttrbutionDlg.GetControlParameter(ref Dia);

                dlg.GetControlParameter(ref Dia);
          //      WriteVariable(defaultfileName, avariable);
				transaction.Start();
               
                 AssignWireAttributionReference(listwiret, Dia);

                      //          ......
				
				transaction.Commit();
			 }
			return result;
		 }

		public static WindowHandle _hWndRevit;

      
      

       

            public static void AssignWiretAction1(Document doc, UIDocument uiDoc, YJKMepElecWeak.WireAttrbutionDlg dia,ref YJKMepElecWeak.WireAssignParameters a)
            {
              
                string statusPrompt = "请选择导线";
                int i = 0;
              //  Selection s1 = uiDoc.Selection;
                Reference r1 = null;
                List <Reference> r2 = new List<Reference>();

                List<Reference> r3 = new List<Reference>();
                int selected = 0;
                XYZ pth = null;

                //        int relativeh = 0;
                double h = 0;
                int iflink = 0;
                int relativeh = 0;
                XYZ ptc = null;

                WiresCorrection.WiresCorrectionAct.SelectionWireFilter selectionWireFilter = new WiresCorrection.WiresCorrectionAct.SelectionWireFilter();
                YJKMepElecWeak.WireAssignParameters Dia =new YJKMepElecWeak.WireAssignParameters();

            label1:
                Selection s1 = uiDoc.Selection;
                i = 0;
                pth = null;
                selected = 0;
                ptc = null;
                mark = 1;
                dia.SetControlParameter(0);
                while (i == 0)
                {

                    try
                    {
                      
                      



                            dia.GetControlParameter(ref Dia);

                            dia.SetControlParameter(1);
                    //     r1 = s1.PickObject(ObjectType.Element,selectionWireFilter,  statusPrompt);
                     //        r1 = s1.PickObject(ObjectType.Element, statusPrompt);
                          // if (r2.Count== 0)
                            {
                               r2 = (List<Reference>)s1.PickObjects(ObjectType.Element, selectionWireFilter, statusPrompt);
                             
                              selected = 1;
                               a = dia.aapara;
                               i = 1;
                        }

                    }
                    catch (Autodesk.Revit.Exceptions.OperationCanceledException ee)
                    { 
                        r2.Clear();
                        if (mark == 1)
                        {
                          
                            i = 1;
                            goto label2;
                        }


                        goto label1;
                    }
                }
                dia.SetControlParameter(0);

                //  assign
         //       Element e=doc.GetElement(r1);
           //     Wire wiret = e as Wire;

                List<Wire> listwiret = new List<Wire>();

                Element e = null;
                Wire wiret = null;
                for (int ki = 0; ki < r2.Count;ki++ )
                {
                    r1 = r2[ki];
                    doc.GetElement(r1);
                    wiret = e as Wire;
                    listwiret.Add(wiret);
                }
            //    AssignWireAttributionReference(listwiret, Dia);
                r2.Clear();
                goto label1;
            label2:

               

                int jk = 0;

            }
            public static void AssignWiretAction(Document doc, UIDocument uiDoc, YJKMepElecWeak.WireAttrbutionDlg dia, ref YJKMepElecWeak.WireAssignParameters a)
            {

                string statusPrompt = "请选择导线";
                int i = 0;
                //  Selection s1 = uiDoc.Selection;
                Reference r1 = null;
                List<Reference> r2 = new List<Reference>();

                List<Reference> r3 = new List<Reference>();
                int selected = 0;
                XYZ pth = null;

                //        int relativeh = 0;
                double h = 0;
                int iflink = 0;
                int relativeh = 0;
                XYZ ptc = null;

                WiresCorrection.WiresCorrectionAct.SelectionWireFilter selectionWireFilter = new WiresCorrection.WiresCorrectionAct.SelectionWireFilter();
                YJKMepElecWeak.WireAssignParameters Dia = new YJKMepElecWeak.WireAssignParameters();

            label1:
                Selection s1 = uiDoc.Selection;
                i = 0;
                pth = null;
                selected = 0;
                ptc = null;
                mark = 1;
                dia.SetControlParameter(0);
                while (i == 0)
                {

                    try
                    {





                        dia.GetControlParameter(ref Dia);

                        dia.SetControlParameter(1);
                        //     r1 = s1.PickObject(ObjectType.Element,selectionWireFilter,  statusPrompt);
                        //        r1 = s1.PickObject(ObjectType.Element, statusPrompt);
                        // if (r2.Count== 0)
                        {
                            r2 = (List<Reference>)s1.PickObjects(ObjectType.Element, selectionWireFilter, statusPrompt);

                            selected = 1;
                            a = dia.aapara;
                            i = 1;
                        }

                    }
                    catch (Autodesk.Revit.Exceptions.OperationCanceledException ee)
                    {
                        r2.Clear();
                        if (mark == 1)
                        {

                            i = 1;
                            goto label2;
                        }


                        goto label1;
                    }
                }
                dia.SetControlParameter(0);

                //  assign
                //       Element e=doc.GetElement(r1);
                //     Wire wiret = e as Wire;

                List<Wire> listwiret = new List<Wire>();

                Element e = null;
                Wire wiret = null;
                for (int ki = 0; ki < r2.Count; ki++)
                {
                    r1 = r2[ki];
                    doc.GetElement(r1);
                    wiret = e as Wire;
                    listwiret.Add(wiret);
                }
                //    AssignWireAttributionReference(listwiret, Dia);
                r2.Clear();
                goto label1;
            label2:



                int jk = 0;

            }
            public static void AssignWireAttributionReference(List <Wire> wirelist, YJKMepElecWeak.WireAssignParameters wiredata)
             {
                 SetWireData(wiredata, wirelist);             
             }
              public List <YJKMepElecWeak.WireTypeSelfDataDef> GetWireType(Document doc1)
              {
                  List<YJKMepElecWeak.WireTypeSelfDataDef> list = new List<YJKMepElecWeak.WireTypeSelfDataDef>();

                  WireTypeSet wireTypes = doc1.Settings.ElectricalSetting.WireTypes;
                  WireTypeSetIterator it = wireTypes.ForwardIterator();

                  while (it.MoveNext())
                  {
                      Object e = it.Current;
                      WireType type = e as WireType;
                      string typename = type.Name;
                      ElementId id = type.Id;
                      YJKMepElecWeak.WireTypeSelfDataDef wireT = new YJKMepElecWeak.WireTypeSelfDataDef(typename, id);
                      int iok = 0;
                      ReadWireSettingGeneralFileXml(wireXmlfileName, doc, typename, ref wireT,ref iok);

                  //    wireT.wireTypeId = id;
                   //   wireT.wireTypeName = type.Name;
                    //  wireT.
                      if (iok==1)
                          list.Add(wireT);

                  }




                  return list;
              }
              public List<YJKMepElecWeak.ConduitTypeSelfDataDef> GetConduitType(Document doc1)
              {
                  List<YJKMepElecWeak.ConduitTypeSelfDataDef> list = new List<YJKMepElecWeak.ConduitTypeSelfDataDef>();
                  if (doc1 != null)
                  {
                      FilteredElementCollector conduitTypeCollector = new FilteredElementCollector(doc1);
                      ICollection<ElementId> collection = conduitTypeCollector.OfClass(typeof(ConduitType)).ToElementIds();
                      foreach (ElementId id in collection)
                      {
                          ConduitType conduitType = doc1.GetElement(id) as ConduitType;
                          if (conduitType != null && conduitType.IsWithFitting)
                          {
                              string typename=conduitType.Name;
                              int iok = 0;
                              YJKMepElecWeak.ConduitTypeSelfDataDef conduitT = new YJKMepElecWeak.ConduitTypeSelfDataDef(typename,id);
                              ReadConduitSettingGeneralFileXml(conduitXmlfileName, doc, typename, ref conduitT,ref iok);
                              if (iok==1)
                                  list.Add(conduitT);
                          }
                      }
                  }
                  return list;
             
              }





         public void ReadWireSettingGeneralFileXml(string XmlfileName, Document doc1,string typename,ref YJKMepElecWeak.WireTypeSelfDataDef wireT,ref int iok)
         {
             
                 string filepath = "Data\\Electrical\\";
                 filespathE = MepGeoFunctions.YJKMEPMath.GetWaterAnyPathFromTrans(filepath);
                string name = XmlfileName;
                string pathaddfile = filespathE + name;
                iok=0;
              
                if (null == doc1)
                 {
                       
                        return ;
                }
                if (System.IO.File.Exists(pathaddfile))
                {

                    XmlHelpDef.XmlHelperSelfDef xmlf = new XmlHelpDef.XmlHelperSelfDef();
                    XmlDocument docxml = new XmlDocument();
                    xmlf.LoadXmlFile(pathaddfile);

                  //   string node = "Wire";
                     string node = "Wire";

                    xmlf.SetNode(node);

                   


                     List<XmlElement> elements = xmlf.GetNodeElements("Wire");
                     int k = 0;
                     foreach (XmlElement current in elements)
                     {
                            string wireTypeName = current.GetAttribute("Name");
                         
                             if (typename == wireTypeName)
                             {
                                    XmlNodeList numTypes = current.ChildNodes;
                                    foreach (XmlElement current2 in numTypes)
                                    {
                                        double key = Convert.ToDouble(current2.GetAttribute("Size"));
                                        double value = Convert.ToDouble(current2.GetAttribute("Ampacity"));;
                                        wireT.WireSizes.Add(key, value);
                                        iok = 1;
                                    }
                               }


                        }

                       





                    }
                return ; 

              }

         public void ReadConduitSettingGeneralFileXml(string XmlCoduitfileName, Document doc1, string typename, ref YJKMepElecWeak.ConduitTypeSelfDataDef conduitT,ref int iok)
         {
             iok = 0;
             string filepath = "Data\\Electrical\\";
             filespathE = MepGeoFunctions.YJKMEPMath.GetWaterAnyPathFromTrans(filepath);
             string name = conduitXmlfileName;
             string pathaddfile = filespathE + name;


             if (null == doc1)
             {

                 return;
             }
             if (System.IO.File.Exists(pathaddfile))
             {

                 XmlHelpDef.XmlHelperSelfDef xmlf = new XmlHelpDef.XmlHelperSelfDef();
                 XmlDocument docxml = new XmlDocument();
                 xmlf.LoadXmlFile(pathaddfile);

                 //   string node = "Wire";
                 string node = "Conduit";

                 xmlf.SetNode(node);




                 List<XmlElement> elements = xmlf.GetNodeElements("Conduit");
                 int k = 0;
                 foreach (XmlElement current in elements)
                 {
                     string wireTypeName = current.GetAttribute("Name");

                     if (typename == wireTypeName)
                     {
                         XmlNodeList numTypes = current.ChildNodes;
                         foreach (XmlElement current2 in numTypes)
                         {
                             string size = current2.InnerText;
                             int key = Convert.ToInt32(size);
                          //   double value = Convert.ToDouble(current2.GetAttribute("Ampacity")); ;
                             //    conduitT.conduitSizes.Add(key, value);
                             conduitT.conduitSizes.Add(key);
                             iok = 1;
                         }
                     }


                 }

             }
             return;

         }
            public void WriteVariable(string fileName, YJKMepElecWeak.WireAssignParameters a)
            {
              
                FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                StreamWriter sw = new StreamWriter(fs); // 创建写入流  
              
                if (sw != null)
                {
                    sw.WriteLine(a.WireTypeName);
                   sw.WriteLine(a.selectedWireType);
                   sw.WriteLine(a.wirenum);
                   sw.WriteLine(a.wiresize);
                   sw.WriteLine(a.layoutmanner);
                   sw.WriteLine(a.loopnumt);
                   sw.WriteLine(a.conduitT);
                   sw.WriteLine(a.selectedconduitType);
                   sw.WriteLine(a.conduitsize);
                   sw.WriteLine(a.conduitheight);
                    
                    sw.Close(); //关闭文件
                }


            }
            public static void SetWireData(YJKMepElecWeak.WireAssignParameters wiredata,List< Wire> wirelist)
            {


                Transaction ts = new Transaction(doc);
                ts.Start("assignwire");
     //   public string loopnumt;
                foreach (Wire wire in wirelist)
                {

                string height = "";
                Parameter parameter = wire.GetParameters("相对标高")[0];
                
                double data =wiredata.conduitheight;
                double edata = UnitUtils.ConvertToInternalUnits(data, DisplayUnitType.DUT_METERS); 

                wire.GetParameters("相对标高").First().Set(edata);

                 parameter = wire.get_Parameter(BuiltInParameter.RBS_ELEC_WIRE_TYPE);
                 height=wiredata.WireTypeName;
                 parameter.Set(height);


                

                height =wiredata.layoutmanner ;
                wire.GetParameters("敷设方式").First().Set(height);

                data = wiredata.wiresize ;
                edata = UnitUtils.ConvertToInternalUnits(data, DisplayUnitType.DUT_SQUARE_MILLIMETERS);
                wire.GetParameters("截面").First().Set(edata);
                height = wiredata.conduitT;
                wire.GetParameters("线管类型").First().Set(height);

                data = wiredata.conduitsize;
                edata = UnitUtils.ConvertToInternalUnits(data, DisplayUnitType.DUT_MILLIMETERS);
                wire.GetParameters("管径").First().Set(edata);


                parameter = wire.get_Parameter(BuiltInParameter.RBS_WIRE_NUM_CONDUCTORS_PARAM);
                int num = wiredata.wirenum;
                if (num < 1)
                    num = 1;
                parameter.Set(num);

             //   parameter = wire.get_Parameter(BuiltInParameter.ELEM_TYPE_PARAM);

            //    parameter = wire.get_Parameter(BuiltInParameter.SYMBOL_ID_PARAM);
                    string wTypeType1=wiredata.WireTypeName;
               
                   // ElementId eid=parameter.AsElementId();
                    
                //    Element e = doc.GetElement(eid);

                    wire.ChangeTypeId( wiredata.selectedWireTypeId);


               //     WireType wType=e as WireType;
                //     parameter = wType.get_Parameter(BuiltInParameter.RBS_ELEC_WIRE_TYPE);
                 //   parameter.Set(wTypeType1);
                }
                ts.Commit();

            }
             public static void SetInitWireExtensionData(Wire wire)
             {
                 Parameter parameter = wire.GetParameters("相对标高")[0];
                 double data = 2.700;
                 double edata = UnitUtils.ConvertToInternalUnits(data, DisplayUnitType.DUT_METERS);




              
                 
                 string height = "";
                
                 wire.GetParameters("相对标高").First().Set(edata);
                 height = "AB";
                 wire.GetParameters("敷设方式").First().Set(height);

                 data = 2.5;
                 edata = UnitUtils.ConvertToInternalUnits(data, DisplayUnitType.DUT_SQUARE_MILLIMETERS);
                 wire.GetParameters("截面").First().Set(edata);
                 height = "PC";
                 wire.GetParameters("线管类型").First().Set(height);

                 data = 20;
                 edata = UnitUtils.ConvertToInternalUnits(data, DisplayUnitType.DUT_MILLIMETERS);
                 wire.GetParameters("管径").First().Set(edata);

             }
            public  static void GetWireAttibute(ref YJKMepElecWeak.WireAssignParameters a ,Wire wire,YJKMepElecWeak.WireAttrbutionDlg dlg)
            { 
        
                a.loopnumt="1";
                if (wire != null)
                {
                    IList<Parameter> lp = dlg.bWire.GetParameters("相对标高");
                    if (lp == null)
                    {
                        Transaction ts = new Transaction(doc, "WireBinding");
                        ts.Start();
                        SetAndOPenExternalSharedParamFile();
                       
                        SetInitWireExtensionData(dlg.bWire);
                        ts.Commit();
                    }
                    else
                    {
                          if (lp.Count == 0)
                          {
                              Transaction ts = new Transaction(doc, "WireBinding");
                              ts.Start();
                              SetAndOPenExternalSharedParamFile();
                            
                              SetInitWireExtensionData(dlg.bWire);
                              ts.Commit();
                          }
                    }
              //      return;
                    Parameter parameter = dlg.bWire.GetParameters("相对标高")[0];
                    double h = parameter.AsDouble();
                    double edata = UnitUtils.ConvertFromInternalUnits(h, DisplayUnitType.DUT_METERS);

                    dlg.aapara.conduitheight = edata;
                    a.conduitheight = edata;
          //         parameter = dlg.bWire.get_Parameter(BuiltInParameter.RBS_ELEC_WIRE_TYPE);
                   parameter = dlg.bWire.get_Parameter(BuiltInParameter.SYMBOL_ID_PARAM);
                  
                //   Parameter parameter1 = dlg.bWire.get_Parameter(BuiltInParameter.RBS_ELEC_CIRCUIT_WIRE_TYPE_PARAM);
               //    ElementId eid1 = parameter1.AsElementId();

            //       Element e1 = doc.GetElement(eid1);

                 //   ElementId eid=parameter.AsElementId();
                    ElementId eid = dlg.bWire.GetTypeId();
                    Element e = doc.GetElement(eid);
                    WireType wType=e as WireType;
                    int k=0;
                    int ifind = 0;
                    foreach (YJKMepElecWeak.WireTypeSelfDataDef wireTypeDef in listWire )
                    {
                        if (wireTypeDef.wireTypeName == wType.Name)
                        {
                         //   dlg.wireTypeList.SelectedItem = k;
                            dlg.aapara.WireTypeName=wType.Name;
                            dlg.aapara.selectedWireType=k;
                            a.WireTypeName = wType.Name;
                            a.selectedWireType = k;
                            a.selectedWireTypeId = wireTypeDef.wireTypeId;
                            ifind = 1;
                            
                            break;
                        }
                        k=k+1;
                    }
                    if (ifind==0)
                    {
                        if (listWire.Count > 0)
                        {
                            YJKMepElecWeak.WireTypeSelfDataDef def = listWire[0];
                            string wireName1 = def.wireTypeName;
                            dlg.aapara.WireTypeName = wType.Name;
                            dlg.aapara.selectedWireType = 0;
                            a.WireTypeName = wType.Name;
                            a.selectedWireType = 0;
                            a.selectedWireTypeId = listWire[0].wireTypeId;
                        }
                    }

                    
                    int i = 0;
                  //  parameter = dlg.bWire.get_Parameter(BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM);
              //      parameter = dlg.bWire.GetParameters("线管类型")[0];
                    
              //       e = parameter.Element;
            //        ConduitType cType = e as ConduitType;
                    ifind = 0;
                    foreach (YJKMepElecWeak.ConduitTypeSelfDataDef conduitTypeDef in listConduit)
                    {
                         
                        if (conduitTypeDef.conduitTypeName == dlg.bWire.GetParameters("线管类型")[0].AsString())
                        {
                            dlg.aapara.conduitT=dlg.bWire.GetParameters("线管类型")[0].AsString();
                            dlg.aapara.selectedconduitType=i;
                            a.conduitT=dlg.bWire.GetParameters("线管类型")[0].AsString();
                            a.selectedconduitType=i;
                            ifind = 1;
                         

                            break;
                        }
                        i = i + 1;
                    }
                    if (ifind == 0)
                    {
                        if (listConduit.Count > 0)
                        {
                            YJKMepElecWeak.ConduitTypeSelfDataDef defc = listConduit[0];
                            string cname = defc.conduitTypeName;
                            dlg.aapara.conduitT = cname;
                            dlg.aapara.selectedconduitType = 0;
                            a.conduitT = cname;
                            a.selectedconduitType = 0;
                        }
                    }

                    string lm = dlg.bWire.GetParameters("敷设方式")[0].AsString();
                    for (int j = 0; j < dlg.layoutnum; j++)
                    {
                        if (dlg.layout[j] == lm)
                        {
                            dlg.aapara.layoutmanner=lm;
                            dlg.aapara.layoutmanneri=j;
                            
                             a.layoutmanner=lm;
                             a.layoutmanneri=j;
                       //     dlg.layoutMode.SelectedIndex = j;
                            break;
                        }
                    }
                    h = dlg.bWire.GetParameters("截面")[0].AsDouble();
                    edata = UnitUtils.ConvertFromInternalUnits(h, DisplayUnitType.DUT_SQUARE_MILLIMETERS);
                    dlg.aapara.wiresize = edata;
                      int wirenum=dlg.bWire.HotConductorNum;
                      if (wirenum<1)
                           wirenum=1;
                      dlg.aapara.wirenum = wirenum;




                       a.wiresize = edata;
                       a.wirenum = wirenum;


                       int h1 = dlg.bWire.GetParameters("管径")[0].AsInteger();

                       int edata1 = (int)UnitUtils.ConvertFromInternalUnits(h1, DisplayUnitType.DUT_MILLIMETERS);
                       a.conduitsize = edata1;
                       dlg.aapara.conduitsize = edata1;
               //        a.selectedconduitType = 0;
                   //    a.selectedWireType = 0;
                 
                }
                 


            
            }
            public static Wire GetWireObj(Document doc1, UIDocument uiDoc1, ref int iok)
            {
                iok = 0;
                Wire wire = null;
                Selection s1 = uiDoc1.Selection;
                try
                {
                    WiresCorrection.WiresCorrectionAct.SelectionWireFilter selectionWireFilter = new WiresCorrection.WiresCorrectionAct.SelectionWireFilter();
                    string prompt = "请选择基准导线";
                    Reference refer = s1.PickObject(ObjectType.Element, selectionWireFilter, prompt);

                    iok = 1;
                    Element e = doc1.GetElement(refer);
                    wire = e as Wire;
                    return wire;
                }
                catch (Autodesk.Revit.Exceptions.OperationCanceledException)
                {

                }


                return wire;
            }
           
            public  static void SetAndOPenExternalSharedParamFile()
            {
                string filepath = "Data\\Electrical\\";
                string filespathE1 = MepGeoFunctions.YJKMEPMath.GetWaterAnyPathFromTrans(filepath);

                string sharenamefile = filespathE1 + sharename;
                application.SharedParametersFilename = sharenamefile;
                //       return application.OpenSharedParameterFile();
                DefinitionFile df = application.OpenSharedParameterFile();
                SetNewParameterToInstanceWire(uiapp, df);

            }
            public  static bool SetNewParameterToInstanceWire(UIApplication app, DefinitionFile myDefinitionFile)
            {
                DefinitionGroups myGroups = myDefinitionFile.Groups;
                  string groupName = "电气数据";
              //    DefinitionGroup myGroup = myGroups.Create(groupName);
          
                DefinitionGroup myGroup = myDefinitionFile.Groups.get_Item(groupName);

          //      Category category = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Wire);
                if (null == myGroup)
                {
                    myDefinitionFile.Groups.Create(groupName); //create a new group, or get an existing group
                } 
                bool instanceBindOK1=true;
                string [] definitionName=new string [10];


                definitionName[0]="管径";
                definitionName[1]="截面";
                definitionName[2]="敷设方式";
                definitionName[3]="线管类型";
                definitionName[4]="相对标高";

                for (int i=0;i<5;i++)
                {
                    Definition myDefinition_ProductDate=GetDefinition(myDefinitionFile,definitionName[i]);
                    CategorySet myCategories = app.Application.Create.NewCategorySet();
                    Category myCategory = app.ActiveUIDocument.Document.Settings.Categories.get_Item(BuiltInCategory.OST_Wire);
                    myCategories.Insert(myCategory);
                    InstanceBinding instanceBing = app.Application.Create.NewInstanceBinding(myCategories);
                    BindingMap bindingMap = app.ActiveUIDocument.Document.ParameterBindings;
                    bool instanceBindOK =true;
                    if (i==0)
                    bindingMap.Insert(myDefinition_ProductDate, instanceBing, BuiltInParameterGroup.PG_LENGTH);
                    else if(i==1)
                    {
                        instanceBindOK = bindingMap.Insert(myDefinition_ProductDate, instanceBing, BuiltInParameterGroup.PG_AREA);
                    }
                    else
                        instanceBindOK = bindingMap.Insert(myDefinition_ProductDate, instanceBing, BuiltInParameterGroup.PG_TEXT);
            }
                return instanceBindOK1;
            }

            public bool SetNewParameterToTypeWire(Autodesk.Revit.ApplicationServices.Application app, DefinitionFile myDefinitionFile)
            {

            //    Application app = this.doc.Application; ;
                DefinitionGroups myGroups = myDefinitionFile.Groups;
                DefinitionGroup myGroup = myGroups.Create("MyParameter");
                ExternalDefinitionCreationOptions edco = new ExternalDefinitionCreationOptions("CompanyName", ParameterType.Text);

                Definition myDefinition_CompanyName = myGroup.Definitions.Create(edco);

                CategorySet myCategories = app.Create.NewCategorySet();  Category myCategory = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Walls);

                myCategories.Insert(myCategory);
                TypeBinding typeBing = app.Create.NewTypeBinding(myCategories);
                BindingMap bindingMap = doc.ParameterBindings;
                bool typeBindOK = bindingMap.Insert(myDefinition_CompanyName, typeBing, BuiltInParameterGroup.PG_TEXT);
                return typeBindOK;
            }
            public static Definition GetDefinition(DefinitionFile myDefinitionFile,string definitionName)
            {
                Definition result=null;
                string groupName = "电气数据";
                foreach(DefinitionGroup myGroup in myDefinitionFile.Groups)
                {
                    if (myGroup.Name == groupName)
                    {
                        foreach (Definition definition in myGroup.Definitions)
                        {
                            if (definition.Name == definitionName)
                            {
                                result = definition;
                                return result;
                            }
                        }
                    }
                }
                return result;
            }

      
         
    
            
        }
            public class WindowHandle : IWin32Window
            {

                public WindowHandle(IntPtr h)
                {
                    this._hwnd = h;
                }

                public IntPtr Handle
                {
                    get
                    {
                        return this._hwnd;
                    }
                }

                public static WindowHandle GetCurrentWindowHandle()
                {
                    return new WindowHandle(Process.GetCurrentProcess().MainWindowHandle);
                }

                private IntPtr _hwnd;

            }
    
}
namespace WiresCorrection0
{
    [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
    [Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)]
    public class WiresCorrectionAct0 : IExternalCommand
    {
        public static Document doc = null;
        public static UIDocument uiDoc = null;
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {


            doc = commandData.Application.ActiveUIDocument.Document;
            uiDoc = commandData.Application.ActiveUIDocument;
            double ver = Convert.ToDouble(commandData.Application.Application.VersionNumber);
            if (ver < 2015.0)
            {
                TaskDialog.Show("", "在Revit 2015及以上版本使用此功能");
                return Result.Succeeded;
            }
            int iokf = 0;
            MepGeoFunctions.YJKMEPMath.GetViewifOk(doc, uiDoc, out iokf);
            if (iokf == 0)
            {
                string messagez = "平面图";
                TaskDialog.Show("请选择", messagez);
                goto label2;
            }
            double angle10 = 0;
            WiresCorrection.WiresCorrectionAct.GetWireAction(angle10,doc, uiDoc);
        label2:
            return Result.Succeeded;
        }
    }
}
    namespace WiresCorrection
{
    [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
    [Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)]
    public class WiresCorrectionAct : IExternalCommand
    {
         public static Document doc = null;
         public static UIDocument uiDoc = null;
         public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
         {
           

             doc = commandData.Application.ActiveUIDocument.Document;
             uiDoc = commandData.Application.ActiveUIDocument;
             double ver=Convert.ToDouble(commandData.Application.Application.VersionNumber);
            if (ver< 2015.0)
             {
                 TaskDialog.Show("", "在Revit 2015及以上版本使用此功能");
                 return Result.Succeeded;
             }
             int iokf=0;
             MepGeoFunctions.YJKMEPMath.GetViewifOk(doc, uiDoc, out iokf);
            if (iokf == 0)
            {
                string messagez = "平面图";
                TaskDialog.Show("请选择", messagez);
                   goto label2;
            }
            double angle10 = 30;
            GetWireAction(angle10,doc, uiDoc);
             label2:
             return Result.Succeeded;
         }

	        public class SelectionWireFilter : ISelectionFilter
	       {
		      public bool AllowElement(Element elem)
		      {
			     if (elem != null && elem is Wire)
			     {
			     	Wire wire = elem as Wire;
			     	return true;
		     	}
			    return false;
		     }

	    	public bool AllowReference(Reference reference, XYZ position)
		   {
			    throw new NotImplementedException();
	    	}
	    }
             
    
            public class ConduitTypeSelfData
            {

            }
        
            public static void GetWireAction(double angle101,Document doc1, UIDocument uiDoc1)
         {
               double anglet = 0;
                 Transaction ts = new Transaction(doc1, "WireCorrection");
                 double dist11 = 0;

                 double angle10 = 0;
                 Selection s1 = uiDoc1.Selection;
                 SelectionWireFilter selectionWireFilter = new SelectionWireFilter();
              //   double angle10 = angle101;

                 AngleInput dlg=new AngleInput ();
                 double angint=0;
                 dlg.ang=angint;
                 if (dlg.ShowDialog() == DialogResult.OK)
                 {
                     angle10 = dlg.ang;
                 }
                 else
                     return;
                 
                 angle10 = MepGeoFunctions.YJKMEPMath.AngleTreatPlus(angle10);
                 if (angle10 > 180)
                     angle10 = angle10 - 180.0;
                 double angle111 = angle10 / 180.0 * MepGeoFunctions.YJKMEPMath.pi;

                 string prompt = "请选择需要转成正交的倒角导线";
                 Reference ref1 = null;
                 try
                 {
                     ref1 = s1.PickObject(ObjectType.Element, selectionWireFilter, prompt);
                 }
                 catch (Autodesk.Revit.Exceptions.OperationCanceledException)
                 {
                     goto label0;
                 }
                 XYZ pickPt = new XYZ(ref1.GlobalPoint.X, ref1.GlobalPoint.Y, 0);

                Element e=doc1.GetElement(ref1);
                 Wire wire = e as Wire;
              
                 List<XYZ> wireptsob = MepGeoFunctions.YJKMEPMath.GetWirePts(wire);
                
                 List<XYZ> wireptso = new  List<XYZ>();
                 XYZ pt10=new XYZ(wireptsob [0].X,wireptsob [0].Y,0);
                 int il1=wireptsob.Count-1;
                 XYZ pt1l = new XYZ(wireptsob[il1].X, wireptsob[il1].Y, 0);
                 double dist00=0;
                 double dist0l=0;
                 MepGeoFunctions.YJKMEPMath.DistancePt(pickPt, pt10, ref dist00);
                 MepGeoFunctions.YJKMEPMath.DistancePt(pickPt, pt1l, ref dist0l);
                 int ilast = 1;
                 if (dist0l < dist00)
                 {
                     ilast = 1;
                     for (int k = 0; k < wireptsob.Count;k++ )
                     {
                         wireptso.Add(wireptsob[k]);
                     }
                 }
                 else
                 {
                     ilast = 0;
                     for (int k = 0; k < wireptsob.Count; k++)
                     {
                         wireptso.Add(wireptsob[wireptsob.Count - 1 - k]);
                     }
                 }
                
                 List<XYZ> wirepts = MepGeoFunctions.YJKMEPMath.GetWirePtsAngle(wireptso, angle111);
                 int ifind = 0;
                 switch(wirepts.Count)
                 {
                     case 0:
                         LocationCurve lCurve = wire.Location as LocationCurve;
                         Line line = lCurve.Curve as Line;
                         XYZ pt1 = line.GetEndPoint(0);
                         XYZ pt2 = line.GetEndPoint(1);
                         wirepts.Add(pt1);
                         wirepts.Add(pt2);
                         break;
                     case 1:
                         goto label0;
                         break;
                     case 2:

                       XYZ pt3 = new XYZ(wirepts[1].X, wirepts[0].Y, wirepts[0].Z);
                       XYZ pt4 = new XYZ(wirepts[0].X, wirepts[1].Y, wirepts[0].Z);



                       double dist1 =0;
                       double dist2 = 0;
                       double dist30 =0;
                       double dist40 = 0;
                       MepGeoFunctions.YJKMEPMath.DistancePt(pt3, wirepts[1], ref dist1);
                       MepGeoFunctions.YJKMEPMath.DistancePt(pt4, wirepts[1], ref dist2); 
                       MepGeoFunctions.YJKMEPMath.DistancePt(pt3, wirepts[0], ref dist30);
                       MepGeoFunctions.YJKMEPMath.DistancePt(pt4, wirepts[0], ref dist40);
                    //   if (ilast==1)
                     //    {
                             if (dist1 >= dist2)
                            {
                              wirepts[1] = pt4;
                            }
                            else
                            {
                              wirepts[1] = pt3;
                            }
                    //     }
                /*       else
                       {
                           if (dist30 >= dist40)
                           {
                               wirepts[0] = pt4;
                           }
                           else
                           {
                               wirepts[0] = pt3;
                           }
                       } */
                          break;
                     case 3:


                         XYZ pt5 = new XYZ(wirepts[2].X, wirepts[0].Y, wirepts[1].Z);
                         XYZ pt6 = new XYZ(wirepts[0].X, wirepts[2].Y, wirepts[1].Z);
                         double dist3 =0;
                         double dist4 = 0;
                         MepGeoFunctions.YJKMEPMath.DistancePt(pt5, wirepts[1], ref dist3);
                         MepGeoFunctions.YJKMEPMath.DistancePt(pt6, wirepts[1], ref dist4);
                         if (dist3 >= dist4)
                         {
                                 wirepts[1] = pt6;
                          }
                          else
                          {
                                 wirepts[1] = pt5;
                          }
                           break;
                     default:
                          for (int i = 1; i < wirepts.Count - 1; i++)
                          {
                              wirepts[i] = GetWireMiddlePt(wirepts[i - 1], wirepts[i], angle111);
                        //      if (i==1)
                              {
                                  MepGeoFunctions.YJKMEPMath.DistancePt(wirepts[i - 1], wirepts[i], ref dist11);
                                  anglet=MepGeoFunctions.YJKMEPMath.AngleProjection(wirepts[i - 1], wirepts[i]);
                                  anglet = anglet / MepGeoFunctions.YJKMEPMath.pi * 180.0;
                              }
                              if (i == wirepts.Count - 2)
                             {
                                  XYZ pt7 = wirepts[i - 1];
                                   XYZ ptlast = wirepts[i];


                                   if (System.Math.Abs(pt7.X-ptlast.X)<MepGeoFunctions.YJKMEPMath.distanceerr)
                                 {
                                     wirepts[i] = new XYZ(wirepts[i].X, wirepts[wirepts.Count - 1].Y, wirepts[i].Z);
                                  }
                                   else if (System.Math.Abs(pt7.Y-ptlast.Y)<MepGeoFunctions.YJKMEPMath.distanceerr)
                                  {
                                      wirepts[i] = new XYZ(wirepts[wirepts.Count - 1].X, wirepts[i].Y, wirepts[i].Z);
                                  }
                                   anglet = MepGeoFunctions.YJKMEPMath.AngleProjection(wirepts[wirepts.Count - 1], wirepts[wirepts.Count - 2]);
                                   anglet = anglet / MepGeoFunctions.YJKMEPMath.pi * 180.0;
                               }
                             }
                            break;
                  }
                 List<XYZ> wirenewpts1 = GetWireTreatVex(wirepts, angle111);

                 List<XYZ> wirenewptsafter = MepGeoFunctions.YJKMEPMath.GetNewVexsWire(wirenewpts1, angle111);

                 MepGeoFunctions.YJKMEPMath.DistancePt(wirenewptsafter[0], wirenewptsafter[1], ref dist11);
                 List<XYZ> wirenewptsafterb = new List<XYZ>();
                 if (ilast == 1)
                 {
                     for (int k = 0; k < wirenewptsafter.Count; k++)
                     {
                         int ib = k;
                         wirenewptsafterb.Add( wirenewptsafter[ib]);
                     }
                 }
                 else
                 {

                 

                         for (int k = 0; k < wirenewptsafter.Count; k++)
                         {
                             int ib = wirenewptsafter.Count - 1 - k;
                             wirenewptsafterb.Add(wirenewptsafter[ib]);
                         }

                 }

                 ts.Start();
                 MepGeoFunctions.YJKMEPMath.SetWireVexs(wire, wireptso, wirenewptsafterb);
                 ts.Commit();
          
         label0:
             int jk = 0;
         }

         public static List<XYZ> GetWireTreatVex(List<XYZ> wirepts,double angle0)
         {
              List<XYZ> wirenewpts=new List<XYZ>();
              wirenewpts.Add(wirepts[0]);
             int j=0;
             int jv=1;
             int ix=1;

          /*  for (int i = 1; i < wirepts.Count; i++)
             {
                 wirenewpts.Add(wirepts[i]);
             }
             return wirenewpts;  */
              if (wirepts.Count<=3)
              {
                  for (int i=1;i<wirepts.Count;i++)
                  {
                        wirenewpts.Add(wirepts[i]);
                  }
                   return wirenewpts;
              }
              else
              {
                     XYZ  ptl=new XYZ (0,0,0);
                     double x1=0;
                     double y1=0;
                     double x2=0;
                     double y2=0;
                     double deltax=0;
                     double deltay=0;
                     x1=wirepts[0].X;
                     y1=wirepts[0].Y;
                     x2=wirepts[1].X;
                     y2=wirepts[1].Y;
                     ptl = wirepts[1];
             //        int ikx=ifxyValue(wirepts[0],wirepts[1],angle0);
                     deltax=x2-x1;
                     deltay=y2-y1;
                     if(System.Math.Abs(deltax)<MepGeoFunctions.YJKMEPMath.distanceerr)
                 //    if (ikx==1)
                     {
                          ix=1;
      
                     }
                     else
                     {
                          ix=0;
                     }
              label0:
                   x1=wirepts[jv].X;
                   y1=wirepts[jv].Y;
                   j=j+1;
                   jv=jv+1;

                  if (jv<wirepts.Count)
                  {
                     x2=wirepts[jv].X;
                     y2=wirepts[jv].Y;
                     deltax=x2-x1;
                     deltay=y2-y1;
                     if(System.Math.Abs(deltax)<MepGeoFunctions.YJKMEPMath.distanceerr)
                    //  if (ikx==1)
                     {
                         if (ix==1)
                         {
                             ptl = wirepts[jv];  
                         }
                         else
                         {
                             wirenewpts.Add(ptl);
                             ptl = wirepts[jv]; 
                             ix = 1;
                         }
                     }
                     else
                     {
                         if (ix == 0)
                         {
                             ptl = wirepts[jv];
                         }
                         else
                         {
                             wirenewpts.Add(ptl);
                             ptl = wirepts[jv];
                             ix = 0;
                         }     
                     }
                      goto label0;
                  }
                  else
                  {
                       wirenewpts.Add(wirepts[wirepts.Count-1]); 
                  }
              }
             return wirenewpts;
         }
         public static int ifxyValue(XYZ pt1, XYZ pt2, double angle0)
         {
             int ik = 0;
             double ang=MepGeoFunctions.YJKMEPMath.AngleProjection(pt1,pt2);
             if (ang < 0)
                 ang = MepGeoFunctions.YJKMEPMath.pi * 2.0 + ang;
             if (ang > MepGeoFunctions.YJKMEPMath.pi)
                 ang = ang - MepGeoFunctions.YJKMEPMath.pi;
             double delta = System.Math.Abs(angle0 - ang);
             if (delta > MepGeoFunctions.YJKMEPMath.pi)
                 delta = delta - MepGeoFunctions.YJKMEPMath.pi;
             if (delta <= MepGeoFunctions.YJKMEPMath.angleerr)
                 ik = 1;
             return ik;

         }

         public static XYZ GetWireMiddlePtbak(XYZ ptFirst, XYZ ptSecond, double angle0)
         {
             double dist = 0;
             MepGeoFunctions.YJKMEPMath.DistancePt(ptFirst, ptSecond, ref dist);

             XYZ secondFirstV = ptSecond - ptFirst;
             double angletoplane = XYZ.BasisX.AngleOnPlaneTo(secondFirstV, XYZ.BasisZ);
             angletoplane = angletoplane -angle0-MepGeoFunctions.YJKMEPMath.pi/2.0;

             double x = System.Math.Abs(dist * System.Math.Sin(angletoplane));
             double y = System.Math.Abs(dist * System.Math.Cos(angletoplane));
             XYZ pt1=new XYZ (ptFirst.X+x*(System.Math.Cos(angle0)),ptFirst.Y+x*(System.Math.Sin(angle0)),0);
             XYZ pt2=new XYZ (ptFirst.X+y*(System.Math.Sin(angle0)),ptFirst.Y-y*(System.Math.Cos(angle0)),0);
             XYZ pt11 = new XYZ(pt1.X, pt1.Y, ptSecond.Z);
             XYZ pt12 = new XYZ(pt2.X, pt2.Y, ptSecond.Z);
             if (x<y)
             {
                 ptSecond = pt12;
             }
             else{
                 ptSecond = pt11;
             }
             //    ptSecond = ptFirst + precos;
             return ptSecond;
         }
         public static XYZ GetWireMiddlePt(XYZ ptFirst, XYZ ptSecond,double angle0)
         {
             double dist =0;
             MepGeoFunctions.YJKMEPMath.DistancePt(ptFirst, ptSecond, ref dist);

             XYZ secondFirstV = ptSecond - ptFirst;
             XYZ pta = new XYZ(0, 0, 0);
             pta=MepGeoFunctions.YJKMEPMath.RotationAngleV(XYZ.BasisX, angle0);
             double angletoplane1 = XYZ.BasisX.AngleOnPlaneTo(secondFirstV, XYZ.BasisZ);
             double angletoplane = pta.AngleOnPlaneTo(secondFirstV, XYZ.BasisZ);

             int num8 = 8;
             int quadrantnum = CircleQuadrant(num8, angletoplane);
             int ifind = 0;
             double x=0;
             double y=0;
             double z=0;

             switch (quadrantnum)
             {
                 case 1 :
                     secondFirstV = XYZ.BasisX;

                       break;
                 case 2:
                       secondFirstV = XYZ.BasisY;
                       ifind = 1;
                      break;
                 case 3:
                      secondFirstV = XYZ.BasisY;
                       ifind = 1;
                      break;
                 case 4:
                      secondFirstV = -XYZ.BasisX;
                      break;
                 case 5:
                      secondFirstV = -XYZ.BasisX;
                     break;
                 case 6:
                     secondFirstV = -XYZ.BasisY;
                     ifind = 1;
                      break;
                 case 7:
                      secondFirstV = -XYZ.BasisY;
                      ifind = 1;
                      break;
                 case 8 :

                      secondFirstV = XYZ.BasisX;
                      break;
             }
             XYZ secondFirstVo = new XYZ(0, 0, 0);
             secondFirstVo = secondFirstV;


             XYZ precos = new XYZ(0, 0, 0);
                 precos = secondFirstV * (dist * System.Math.Abs(System.Math.Cos(angletoplane)));

                 XYZ presin = new XYZ(0, 0, 0);
                 presin = secondFirstV * (dist * System.Math.Abs(System.Math.Sin(angletoplane)));
             if (ifind==1)
                 ptSecond = ptFirst + presin;
            else
                ptSecond = ptFirst + precos;
             return ptSecond;
         }

      
         public static int CircleQuadrant(int num,double angle)
         {
              double delta=0;
              delta=MepGeoFunctions.YJKMEPMath.pi*2.0/num;
             for (int i = 0; i < num;i++ )
             {
                 double angle1 = delta * i;
                 double angle2 = delta * (i + 1);
                 if(i==0)
                 {
                    if (angle > angle1 && angle <= angle2)
                   {
                     return i + 1;
                   }
                 }
                 else
                 {
                     if (i == num - 1)
                     {
                         if (angle > angle1)
                             return num;

                     }
                     else
                     {
                         if (angle > angle1 && angle <= angle2)
                         {
                             return i + 1;
                         }
                     }
                 }
             }
                 return num;
         }

         // Assist.RevitVersionFuncs
         public static void WireConnect(Reference wireref1, Reference wireref2,ref int  iok)
         {
             iok = -1;
             Wire wire1 = doc.GetElement(wireref1) as Wire;
             Wire wire2 = doc.GetElement(wireref2) as Wire;
             if (wire1.Id == wire2.Id)
                 iok = 1;
             List<XYZ> list1 = new List<XYZ>();
             List<XYZ> list2 = new List<XYZ>();
             list1 = MepGeoFunctions.YJKMEPMath.GetWirePts(wire1);
             if (iok != 1)
                 list2 = MepGeoFunctions.YJKMEPMath.GetWirePts(wire2);
             else
                 list2 = list1;
// min distance
             double listdis = 10000000.0;
             int list1vex = 0,list2vex =0 ;
             for (int i = 0; i < list1.Count; i++)
             {
                 XYZ list1pt = list1[i];
                 for (int j = 0; j < list2.Count; j++)
                 {
                     XYZ list2pt = list2[j];
                     if (i==0&&j==0)
                         listdis = list1pt.DistanceTo(list2pt);
                     else
                     {
                         if (list1pt.DistanceTo(list2pt) < listdis)
                           {

                              list1vex = i;
                              list2vex = j;
                              listdis = list1pt.DistanceTo(list2pt);
                          }
                     }
                 }
             }


             int vex1 = 0, vex2 = 0;
             if (list1vex == 0)
             {
                 vex1 = 1;
             }
             else
             {
                 vex1 = list1vex - 1;
             }
        
             if (list2vex == 0)
             {
                 vex2 = 1;
             }
             else
             {
                 vex2 = list2vex - 1;
             }
             Line line1 = Line.CreateBound(list1[vex1], list1[list1vex]);
             Line line2 = Line.CreateBound(list2[vex2], list2[list2vex]);
             XYZ vector1 = (line1.GetEndPoint(1) - line1.GetEndPoint(0)).Normalize();
             XYZ vector2 = (line2.GetEndPoint(1) - line2.GetEndPoint(0)).Normalize();
             if (vector1.IsAlmostEqualTo(vector2) || vector1.IsAlmostEqualTo(-vector2))
             {
                 XYZ endPoint = line1.GetEndPoint(1);
                 wire2.InsertVertex(list2vex, endPoint);
                 wire2.RemoveVertex(list2vex + 1);
                  MepGeoFunctions.YJKMEPMath.ConnectTwoWire(wire1, wire2);
                 return;
             }
             IntersectionResultArray intersectionResultArray = new IntersectionResultArray();
             line2.Intersect(line1, out intersectionResultArray);
             if (intersectionResultArray != null)
             {
                 MessageBox.Show("选择的导线相交，请重新选择。", "YJK提示");
                 return;
             }
             Line line4 = Line.CreateUnbound(list1[vex1], list1[list1vex] - list1[vex1]);
             Line line3 = Line.CreateUnbound(list2[vex2], list2[list2vex] - list2[vex2]);
             line3.Intersect(line4, out intersectionResultArray);
             XYZ vertexPoint;
             if (intersectionResultArray != null)
             {
                 vertexPoint = intersectionResultArray.get_Item(0).XYZPoint;
                 try
                 {
                     wire1.InsertVertex(list1vex, vertexPoint);
                     wire1.RemoveVertex(list1vex + 1);
                 }
                 catch
                 {
                 }
                 try
                 {
                     wire2.InsertVertex(list2vex, vertexPoint);
                     wire2.RemoveVertex(list2vex + 1);
                     goto label1;
                 }
                 catch
                 {
                     goto label1;
                 }
             }
             vertexPoint = list1[list1vex];
             wire2.InsertVertex(list2vex, vertexPoint);
             wire2.RemoveVertex(list2vex + 1);
             label1:
             MepGeoFunctions.YJKMEPMath.ConnectTwoWire(wire1, wire2);
         }


      


    }
}
